# -*- coding:utf-8 -*-
"""
作者：王凯
日期：2024年06月15日
"""
import requests  # 导入requests模块
from lxml import etree  # 导入lxml模块
import csv  # 导入csv模块


def getWeather(url):  # 定义函数getWeather
    weather_info = []  # 定义空列表weather_info

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
    }  # 设置请求头
    resp = requests.get(url, headers=headers)  # 发送请求，获取响应
    resp_html = etree.HTML(resp.text)  # 解析响应内容，得到HTML文档对象
    resp_list = resp_html.xpath('//ul[@class="thrui"]/li')  # 得到天气信息列表

    for li in resp_list:  # 遍历天气信息列表
        # 定义空字典day_weather_info
        day_weather_info = {}  # 定义空字典day_weather_info
        day_weather_info['date_time'] = li.xpath('./div[1]/text()')[0].split(' ')[0]  # 日期时间
        day_weather_info['weekday'] = li.xpath('./div[1]/text()')[0].split(' ')[1]  # 星期几
        high = li.xpath("./div[2]/text()")[0]
        day_weather_info['high'] = high[:high.find('℃')]
        low = li.xpath("./div[3]/text()")[0]
        day_weather_info['low'] = low[:low.find('℃')]
        day_weather_info['weather'] = li.xpath("./div[4]/text()")[0]  # 天气状况
        weather_info.append(day_weather_info)  # 将天气信息字典添加到weather_info列表
        #  print(day_weather_info)  # 打印天气信息字典
    return weather_info  # 返回天气信息列表


weathers = []  # 定义空列表weathers
for month in range(1, 13):  # 遍历1-12月
    if month < 10:  # 若月份小于10，则在月份前面加0
        weather_time = '2023'+('0'+str(month))  # 构造月份
    else:     # 否则直接用月份
        weather_time = '2023'+str(month)  # 构造月份
    #  print(weather_time)
    url = 'https://lishi.tianqi.com/fuzhou1/{}'.format(weather_time)  # 构造天气网址
    weather = getWeather(url)  # 调用getWeather函数，获取天气信息列表
    weathers.append(weather)    # 将天气信息列表添加到weathers列表
#  print(weathers)  # 打印weathers列表
#  print(weathers[0][0]['date_time'])
with open('weather.csv', 'w', newline='') as csvfile:  # 打开csv文件
    writer = csv.writer(csvfile)  # 定义csv写入器
    writer.writerow(['日期', '星期', '最高气温', '最低气温', '天气'])  # 写入标题行
    list_year = []  # 定义空列表list_year
    for month_weather in weathers:  # 遍历weathers列表
        for day_weather_dict in month_weather:  # 遍历月份天气信息列表
            list_year.append(list(day_weather_dict.values()))  # 将字典的值添加到list_year列表
    writer.writerows(list_year)  # 写入csv文件

